package com.sinodata.bsm.cicp.finder.solaris;

import java.io.BufferedReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.log4j.Logger;

import com.sinodata.bsm.cicp.util.CommandReader;

/**
 * Solaris操作系统发现程序
 * 程序返回：主机名，CPU核数，操作系统类型，主机型号和操作系统版本
 */
public class OS extends SolarisFinder {

    private static final Logger logger = Logger.getLogger(OS.class);
    //private static final String SHELL = "uname -a";
    private static final String SHELL = "echo `uname -a` `psrinfo|wc -l`";

    @SuppressWarnings("unchecked")
    @Override
    public List<String[]> find(String ip, Map params) {
        List<String[]> list = new ArrayList<String[]>();
        String[] osRes = null;
        BufferedReader reader = null;
        String strLine = null;
        String ptnStr = "(.+)\\s+(.+)\\s+(.+)\\s+(.+)\\s+(.+)\\s+(.+)\\s+(.+)\\s+(\\d+).*";
        try {
            reader = CommandReader.getReader(ip, SHELL, 0, 0);
            Pattern pattern = Pattern.compile(ptnStr);
            strLine = reader.readLine();
            Matcher matcher = pattern.matcher(strLine);
            if (matcher.find()) {
                String hostName = null;
                String cpuNumber = null;
                String osType = null;
                String hostModle = null;
                String osEdition = null;
                osRes = new String[8];
                list.add(osRes);
                osRes[0] = "0";
                osRes[1] = "OS";
                osRes[2] = getHostName(ip) + " OS";
                hostName = matcher.group(2); //主机名
                cpuNumber = matcher.group(8);
                osType = matcher.group(1); //OS类型
                hostModle = matcher.group(5) + " " + matcher.group(6) + " " + matcher.group(7); //主机型号
                osEdition = matcher.group(3); //OS版本
                osRes[3] = hostName;
                osRes[4] = cpuNumber;
                osRes[5] = osType;
                osRes[6] = hostModle;
                osRes[7] = osEdition;
            }
            return list;
        } catch (IOException e) {
            logger.error("failed to find Solaris OS", e);
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e) {
                    logger.error("failed to close reader", e);
                }
            }
        }
        return null;
    }

}
